package main;

import framework.fault.FaultTolerantPeer;
import framework.system.BackEnd;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.HashMap;


public class Peer  {

	private static BackEnd backEnd;
	private static HashMap<String,FaultTolerantPeer> peers = new HashMap<String,FaultTolerantPeer>();

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			String host = "localhost";
			String port = Integer.toString(Registry.REGISTRY_PORT);

			Registry registry = LocateRegistry.getRegistry(host, Registry.REGISTRY_PORT);
			backEnd = (BackEnd) registry.lookup(
					"rmi://" + host + ":" + port + "/" + BackEnd.SERVICENAME);

			String welcome = "" +
				"Welcome to the Peer UI!" + "\n" +
				"_______________________" + "\n" +
				"Commands:" + "\n" +
				"\t" + "list" + "\t...\t" + "Lists all active Peers." + "\n" +
				"\t" + "join <Name>" + "\t...\t" + 
					"Creates a Peer with the given <Name> and joins the network." + "\n" +
				"\t" + "leave <Name>" + "\t...\t" + 
					"The Peer with the given <Name> leaves the network in a regular way." + "\n" +
				"\t" + "crash <Name>" + "\t...\t" + 
					"The Peer with the given <Name> crashes." + "\n";
			System.out.println(welcome);

			BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
			String line;
			while (! (line=in.readLine()).equalsIgnoreCase("exit") ){
				handleRequest(line.split(" "));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static void handleRequest(String[] split) throws Exception {
		String command = split[0];
		if (command.equals("list")) {
			for (String key : peers.keySet()) {
				System.out.print(key+"\t");
			}
			System.out.println();
		} else if (command.equals("join")) {
			FaultTolerantPeer peer = new FaultTolerantPeer(backEnd, split[1], 0);
			peers.put(split[1], peer );
			peer.join();
		} else if (command.equals("leave")) {
			FaultTolerantPeer peer = peers.remove(split[1]);
			peer.leave();
		} else if (command.equals("crash")) {
			FaultTolerantPeer peer = peers.remove(split[1]);
			peer.crash();
		} 
	}
}
